package com.tc.property.config.impl;

import com.tc.property.config.AbstractConfig;
import com.tc.property.config.handler.IConfigSourceChangedHandler;
import com.tc.property.config.model.ConfigItem;
import com.tc.property.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;

public class FileConfig extends AbstractConfig {

	private static Logger LOGGER = LoggerFactory.getLogger(FileConfig.class);

	public FileConfig(String source, Boolean ignoreResourceNotFound) {
		super(source, ignoreResourceNotFound);
	}

	@Override
	public Map<String, ConfigItem> getConfig(List<IConfigSourceChangedHandler> handlers) {
		Map<String, ConfigItem> contextItemMap = new HashMap<String, ConfigItem>();
		String filePath = "";
		try {
			Properties props = new Properties();
			filePath = source.replace(Constants.FILE_PREFIX, Constants.EMPTY_STRING);
			FileInputStream inputStream = new FileInputStream(new File(filePath));
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			//props.load(new BufferedReader(new InputStreamReader(inputStream)));
			props.load(bufferedReader);
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			
			Set<Entry<Object, Object>> entrySet = props.entrySet();
			for (Entry<Object, Object> entry : entrySet) {
				String key = entry.getKey() + "";
				contextItemMap.put(key,
						new ConfigItem(key, entry.getValue() + "", source, 0L, System.currentTimeMillis()));
			}
		} catch (Exception ex) {
			LOGGER.warn("Could not load config from " + source + ": " + ex.getMessage());

			if (!ignoreResourceNotFound) {
				throw new RuntimeException(ex);
			}
		}
		return contextItemMap;
	}

}
